<template>
	<div class="w-[60vw] mx-auto">
		<div v-for="(item, index) in page.commentList" :key="index" class="flex justify-between border-b-2 pb-2 mb-2">
			<div class="flex w-1/2">
				<div>
					<el-avatar :size="50" :src="item.reply.member.avatar" />
				</div>
				<div class="ml-5 flex flex-col justify-between w-full">
					<div>
						<span class="text-red-400"> {{ item.reply.member.username }}</span> 回复了我的评论
					</div>
					<div class="truncate">
						{{ item.reply.content.message }}
					</div>
					<div class="flex">
						<div class="">{{ item.reply.createTime }}</div>
						<div class="mx-2 cursor-pointer" @click="reply(item)">回复</div>
					</div>
					<div class="flex" v-if="commentPostVo.replyedId === item.reply.id">
						<el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="commentPostVo.message" />
						<el-button type="primary" class="ml-2 !h-full" @click="submit"> 发表</el-button>
					</div>
				</div>
			</div>
			<div class="truncate">{{ item.myComment }}</div>
		</div>

		<el-pagination
			style="margin-bottom: 20px"
			background
			layout="prev, pager, next"
			:page-count="page.pages"
			v-model:current-page="page.page"
			@update:current-page="load"
		/>
	</div>
</template>

<script setup>
import { addComment, getAnwserMe } from "@/api/comment";
import { onMounted, reactive } from "vue";
import { useUserStore } from "@/stores/userStores";
import { ElMessage } from "element-plus";

const userStore = useUserStore();
const userInfo = userStore.getUserInfo();
const page = reactive({
	commentList: [],
	page: 1,
	size: 10,
	total: 0,
	pages: 0,
});

const load = async () => {
	const result = await getAnwserMe(page.page, page.size);
	if (result.success) {
		page.commentList = result.data.list;
		page.page = result.data.pageNum;
		page.size = result.data.size;
		page.pages = result.data.pages;
		page.total = result.data.total;
	}
};
const reply = (item) => {
	commentPostVo.otherId = item.reply.otherId;
	commentPostVo.root = item.reply.root;
	commentPostVo.parent = item.reply.parent;
	commentPostVo.replyedId = item.reply.id;
};

const commentPostVo = reactive({
	otherId: null,
	root: 0,
	parent: 0,
	message: "",
	replyedId: 0,
	replyId: userInfo.id,
});

const submit = async () => {
	const result = await addComment(commentPostVo);
	if (result.success) {
		commentPostVo.message = "";
		commentPostVo.replyedId = 0;
		commentPostVo.root = 0;
		commentPostVo.parent = 0;
		ElMessage.success("回复成功");
		load();
	} else {
		ElMessage.error(result.msg ?? "回复失败");
	}
};

onMounted(() => {
	load();
});
</script>

<style scoped></style>
